package org.example.nio;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/23 14:31
 */
public class MultiplexerTimeServer implements Runnable {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(MultiplexerTimeServer.class);

    private Selector selector;
    private ServerSocketChannel servChannel;
    private volatile boolean stop;

    public MultiplexerTimeServer(int port) {
        try {
            this.selector = Selector.open();
            this.servChannel = ServerSocketChannel.open();
            this.servChannel.configureBlocking(false);
            this.servChannel.socket().bind(new InetSocketAddress(port), 1024);
            this.servChannel.register(this.selector, SelectionKey.OP_ACCEPT);
            log.info("The time server is start in port : {}", port);
        } catch (IOException e) {
            log.error("error=", e);
            System.exit(1);
        }

    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        while (!this.stop) {
            try {
                this.selector.select(1000);

                for (SelectionKey key : this.selector.selectedKeys()) {
                    try {
                        this.handleInput(key);
                    } catch (IOException e) {
                        log.error("error=", e);
                        key.cancel();
                        if (key.channel() != null) {
                            key.channel().close();
                        }
                    } finally {
                        this.selector.selectedKeys().remove(key);
                    }
                }
            } catch (IOException e) {
                log.error("error=", e);
            }
        }

        if (!Objects.isNull(selector)) {
            try {
                selector.close();
            } catch (IOException e) {
                log.error("error=", e);
            }
        }
    }

    private void handleInput(SelectionKey key) throws IOException {
        if (!key.isValid()) {
            return;
        }

        // 处理新接入的请求
        if (key.isAcceptable()) {
            final ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
            final SocketChannel sc = ssc.accept();
            sc.configureBlocking(false);
            sc.register(this.selector, SelectionKey.OP_READ);
        }

        // 处理可读取的请求
        if (key.isReadable()) {
            final SocketChannel sc = (SocketChannel) key.channel();
            final ByteBuffer readBuffer = ByteBuffer.allocate(1024);

            final int readBytes = sc.read(readBuffer);
            if (readBytes > 0) {
                readBuffer.flip();

                final byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);

                final String body = new String(bytes, StandardCharsets.UTF_8);
                log.info("The time server receive order : {}", body);

                final String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)
                        ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                this.doWrite(sc, currentTime);
            } else {
                if (readBytes < 0) {
                    key.cancel();
                }
            }
        }
    }

    private void doWrite(SocketChannel channel, String response) throws IOException {
        if (StringUtils.isNotBlank(response)) {
            final byte[] bytes = response.getBytes();
            final ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);

            writeBuffer.put(bytes);
            writeBuffer.flip();

            channel.write(writeBuffer);
        }
    }

}